package gov.pbc.nn.kjgl.software.dao;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.bdf.service.DeptService;
import gov.pbc.nn.core.dao.AbstractHibernateDao;
import gov.pbc.nn.core.dao.PbcnnCoreHibernateDao;
import gov.pbc.nn.core.utils.SecurityUtils;
import gov.pbc.nn.kjgl.Constants;
import gov.pbc.nn.kjgl.entity.DeclareTime;
import gov.pbc.nn.kjgl.entity.Project;
import gov.pbc.nn.kjgl.entity.ProjectFile;
import gov.pbc.nn.uflo.entity.Opinion;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.record.ScenarioProtectRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IDept;
import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.uflo.client.service.TaskClient;
import com.bstek.uflo.model.task.Task;
import com.bstek.uflo.service.TaskOpinion;

@Repository
public class ProjectDao extends AbstractHibernateDao {

	@Resource(name = PbcnnCoreHibernateDao.BEAN_ID)
	private PbcnnCoreHibernateDao pbcnnCoreHibernateDao;

	@Autowired
	@Qualifier(TaskClient.BEAN_ID)
	private TaskClient taskClient;

	@Autowired
	@Qualifier(DeptService.BEAN_ID)
	private DeptService deptService;

	public void saveProject(List<Project> project) {
		for (Project pro : project) {
			EntityState state = EntityUtils.getState(pro);
			if (state.equals(EntityState.NEW)) {
				pro.setProjectTime(new Date());
				pro.setQubie("0");
				pro.setProjectDept(ContextHolder.getLoginUser().getDepts().get(0).getId());
				pro.setDeptName(ContextHolder.getLoginUser().getDepts().get(0).getName());
				pro.setState(0);// 状态0表示新建
				this.save(pro);
			} else if (state.equals(EntityState.MODIFIED)) {
				this.update(pro);
			}
		}
	}

	/**
	 * NewProject视图的维护方法
	 * 
	 * @param project
	 */
	public void saveProjectToo(List<Project> project) {
		for (Project pro : project) {
			EntityState state = EntityUtils.getState(pro);
			if (state.equals(EntityState.NEW)) {
				pro.setProjectTime(new Date());
				pro.setQubie("1");
				pro.setProjectDept(ContextHolder.getLoginUser().getDepts().get(0).getId());
				pro.setDeptName(ContextHolder.getLoginUser().getDepts().get(0).getName());
				pro.setState(10);// 为了方便测试所创建的页面，所以一创建状态就是已通过的
				this.save(pro);
			} else if (state.equals(EntityState.MODIFIED)) {
				this.update(pro);
			}
		}
	}

	public synchronized boolean check(String filename, String projectId) {
		String hql = "select COUNT(*) from ProjectFile where  invalid=false and ownerId=:projctId and fileName=:fileName";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("fileName", filename);
		map.put("projctId", projectId);
		int count = this.queryForInt(hql, map);
		if (count == 0) {
			return true;
		} else {
			return false;
		}
	}

	public void saveProjectFile(String fileName, String pathId) {
		ProjectFile entity = new ProjectFile();
		entity.setFileName(fileName);
		entity.setPath(pathId);
		entity.setCreateUser(ContextHolder.getLoginUserName());
		entity.setCreateDate(new Date());
		entity.setType(0);
		this.save(entity);
	}

	public String getProjectFileId(String fileName, String pathId) {
		String hql = "select id from ProjectFile where fileName=:fileName and path=:pathId and invalid=false";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("fileName", fileName);
		map.put("pathId", pathId);
		List<String> ls = this.query(hql, map);
		return ls.get(0);
	}

	public void deleteProject(List<String> list) {
		for (String id : list) {
			this.delete(id, Project.class);
		}
	}

	public ProjectFile getProjectFileById(String id) {
		String hql = "from ProjectFile where id=:id and invalid=false";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<ProjectFile> ls = this.query(hql, map);
		if (ls.size() > 0) {
			return ls.get(0);
		}
		return null;
	}

	public void deleteFile(String id) {
		if (getProjectFileById(id) != null) {
			this.delete(id, ProjectFile.class);
		}
	}

	public void commitKjcsh(Project project, int type) {
		this.save(project);
	}

	public List<Map<String, Object>> loadDepts(String name) {
		String hql = "select id,name from " + Dept.class.getName();
		List<Object[]> list = null;
		if (StringUtils.isNotEmpty(name)) {
			name = StringUtils.trim(name);
			hql += " where name like :name order by id";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("name", "%" + name + "%");
			list = this.pbcnnCoreHibernateDao.query(hql, params);
		} else {
			hql += "  order by id";
			list = this.pbcnnCoreHibernateDao.query(hql);
		}
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		for (Object[] array : list) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", array[0]);
			map.put("name", array[1]);
			result.add(map);
		}
		return result;
	}

	public boolean getDeclareTime() {
		Date date = new Date();
		Calendar year = Calendar.getInstance();
		int y = year.get(Calendar.YEAR);
		String hql = "select endTime from DeclareTime where invalid=false and year =:year order by year";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("year", y);
		List<Date> ls = this.query(hql, map);
		if (!ls.isEmpty()) {
			for (Date d : ls) {
				if (date.getTime() < d.getTime()) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 根据id得到project，
	 * 
	 * @param id
	 * @auther jack.zhao
	 * @return
	 */
	public Project getProjectById(String id) {
		String hql = "from Project where id=:id and invalid=false";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<Project> ls = this.query(hql, map);
		if (ls.size() > 0) {
			return ls.get(0);
		} else {
			return null;
		}
	}

	public List<Map<String, Object>> selectXmshy() {
		Dept dept = (Dept) ContextHolder.getLoginUser().getDepts().get(0);
		List<IUser> ls = SecurityUtils.getUserByRoleForDeptWithChildren(SecurityUtils.getZZByDept(dept).getId(),
				Constants.ROLE_LXSHY);
		List<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
		if (!ls.isEmpty()) {
			for (IUser i : ls) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("CNAME_", i.getCname());
				map.put("USERNAME_", i.getUsername());
				values.add(map);
			}
		}
		return values;
	}

	@Transactional
	@Expose
	public void zghldSh(String taskId, String opinionText, int i) {
		TaskOpinion option = new TaskOpinion(opinionText);
		Task task = taskClient.getTask(Long.valueOf(taskId));
		taskClient.start(Long.valueOf(taskId));
		final Opinion o = new Opinion();
		o.setProcessInstanceId(task.getProcessInstanceId());
		o.setBusKey(task.getBusinessId());
		o.setTaskId(Long.parseLong(taskId));
		o.setTaskName(task.getTaskName());
		o.setProcessName("非集中式立项申请");
		o.setBusTable("T_PROJECT");
		o.setOpinion(opinionText);
		o.setUsername(ContextHolder.getLoginUser().getUsername());
		o.setDeptId(ContextHolder.getLoginUser().getDepts().get(0).getId());
		o.setDeptName(ContextHolder.getLoginUser().getDepts().get(0).getName());
		o.setCname(ContextHolder.getLoginUser().getCname());
		o.setNodeName(task.getNodeName());
		this.pbcnnCoreHibernateDao.save(o);
		Map<String, Object> map = new HashMap<String, Object>();
		int agree = 0;
		String state = null;
		if (i == 1) {
			state = "28";// 流程变量state设置为28表示主管行领导同意
			agree = 1;
		} else if (i == 0) {
			state = "29";// 流程变量state设置为29表示主管行领导不同意
			agree = 0;
		}
		map.put("agree", agree);
		map.put("state", state);
		taskClient.complete(Long.valueOf(taskId), map, option);
	}
}
